<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 二叉树的最小深度
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(6)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        // c.left = f
        // c.right = g
        /* 
            时间复杂度：O(n)
            空间复杂度：O(n)，n最大为树的宽度，树的最大宽度是树的节点数除以2
        */
        // 写出层序遍历的代码
        var minDepth = function (root) {
            if (!root) {
                return 0
            }
            // 把节点和当前的层级同时存到queue上面去
            let queue = [{node: root, level: 1}]
            let min = Infinity
            while (queue.length > 0) {
                // 每一个数据记录节点和层级，
                let {node, level} = queue.shift()
                // 叶子节点
                if (!node.left && !node.right) {
                    min = Math.min(level, min)
                }
                node.left && queue.push({node: node.left, level: level + 1})
                node.right && queue.push({node: node.right, level: level + 1})
            }
            return min
        };
        console.log(minDepth(a));
    </script>
</body>

</html>